package com.mark.util;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Date;
import java.util.Properties;

/**
 * @Author: MARK
 * @Date: 2019/8/24 19:18
 * @Version: 1.0.0
 * @Description: JavaMail封装的工具类
 */
public class MailUtil {
    //发件人地址
    private static String senderAddress = "xxx@163.com";
    //收件人地址
    private static String  receiptAddress = "xxx@qq.com";
    //发件人账户名
    private static String senderAccount = "xxx";
    //发件人账户密码
    private static String senderPassword = "xxx";

    public static void send() throws Exception {
        //1. 连接邮件服务器的参数配置
        Properties properties = new Properties();
        //设置用户认证方式
        properties.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        properties.setProperty("mail.transport.protocol", "smtp");
        //设置发件人SMTP服务器地址
        properties.setProperty("mail.smtp.host", "smtp.163.com");

        //2. 创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getInstance(properties);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        //3. 创建邮件的实例对象
        Message message = getMimeMessage(session);
        //4. 根据session对象获取邮件传输对象Transport
        Transport transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect(senderAccount, senderPassword);
        //发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        //5. 关闭邮件链接
        transport.close();

    }

    /**
     * @return
     * @create: 2019/8/24
     * @author MARK
     * @Description: 获得创建一封邮件的实例对象
     */
    public static MimeMessage getMimeMessage(Session session) throws Exception {
        //创建一封邮件的实例对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //设置发件人地址
        mimeMessage.setFrom(new InternetAddress(senderAddress));
        /**
         * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC：抄送
         * MimeMessage.RecipientType.BCC：密送
         */
        mimeMessage.setRecipient(RecipientType.TO, new InternetAddress(receiptAddress));
        //设置邮件主题
        mimeMessage.setSubject("JavaMail测试", "utf-8");
        //设置邮件正文
        mimeMessage.setContent("纯文本邮件", "text/html;charset=utf-8");
        //设置发送时间，默认立即发送
        mimeMessage.setSentDate(new Date());
        return mimeMessage;
    }
}
